package cn.gzten.lambda.runtime.util;

import cn.gzten.lambda.runtime.exception.AppServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    public static final ObjectMapper INSTANCE = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    public static <T> T fromJson(String json, Class<T> type) {
        try {
            return INSTANCE.readValue(json, type);
        } catch (JsonProcessingException e) {
            throw new AppServiceException(e);
        }
    }

    public static String toJson(Object o) {
        try {
            return INSTANCE.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new AppServiceException(e);
        }
    }
}
